import datetime

from elasticsearch_dsl import Document, Date, Boolean, \
    Keyword
from utils.serializer import ModelSerializer
from elasticsearch_dsl.search import Search


class BaseDocument(Document):
    enterprise_id = Keyword()
    creator_id = Keyword()
    updator_id = Keyword()
    create_time = Date(default_timezone='UTC')
    update_time = Date(default_timezone='UTC')
    is_deleted = Boolean()
    delete_time = Date(default_timezone='UTC')

    def save(self, validate=False, **kwargs):
        return super(BaseDocument, self).save(validate=validate, **kwargs, using=self.meta_config["client"])

    @classmethod
    def init(cls, **kwargs):
        return super(BaseDocument, cls).init(using=cls.meta_config["client"], index=cls.meta_config["index"])

    @classmethod
    def search(cls, extra={}):
        return Search(
            using=cls.meta_config["client"],
            index=cls.meta_config["index"],
            doc_type=[cls],
            extra=extra
        )

    @classmethod
    def get(cls, id, **kwargs):
        return super(BaseDocument, cls).get(id, using=cls.meta_config["client"], index=cls.meta_config["index"])

    @classmethod
    def mget(cls, docs, **kwargs):
        return super(BaseDocument, cls).mget(docs, using=cls.meta_config["client"], index=cls.meta_config["index"])

    def delete(self, **kwargs):
        return super(BaseDocument, self).delete(using=self.meta_config["client"], index=self.meta_config["index"])

    def update(self, **kwargs):
        return super(BaseDocument, self).update(using=self.meta_config["client"], index=self.meta_config["index"])

    def set_deleted(self):
        self.is_deleted = True

        self.delete_time = datetime.datetime.utcnow()
        self.save()

    @classmethod
    def get_fields(cls):
        return {i[0]: i for i in cls._ObjectBase__list_fields()}
